package com.jewel.controller;

import com.jewel.model.User;
import com.jewel.pojo.TabUser;
import com.jewel.service.LoginService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;


@Controller
public class LoginController {

    @Autowired
    private LoginService loginService;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView index(){
        ModelAndView modelAndView = new ModelAndView();

        modelAndView.setViewName("login");

        return  modelAndView;
    }

    @RequestMapping(value = "/login.do", method = RequestMethod.POST)
    public ModelAndView login(User user, HttpSession httpSession){
        ModelAndView modelAndView = new ModelAndView();

        if (this.loginService.loginIsSuccess(user.getUsername(), user.getPassword())){
            TabUser user1 = this.loginService.getUserByTelephone(user.getUsername());
            httpSession.setAttribute("username", user1.getName());
            httpSession.setAttribute("userId", user1.getUserId());

            modelAndView.setViewName("redirect:/index");
        } else {
            modelAndView.setViewName("redirect:/login");
        }

        return  modelAndView;
    }
}
